package guava;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import org.junit.Test;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * ListenableFuture: 可监听的Future
 * 对java.util.concurrent.Future的扩展增强
 * 文章地址：http://www.xx566.com/detail/158.html
 * User: Realfighter
 * Date: 2014/11/2
 * Time: 13:50
 */
public class ListenableFutureTest {

    @Test
    public void testListenableFuture() {

        ExecutorService executor = Executors.newCachedThreadPool();
        Future<Integer> future = executor.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                //这里调用一些处理逻辑
                return 1 + 1;
            }
        });
        ListeningExecutorService executorService =
                MoreExecutors.listeningDecorator(executor);

        int NUM_THREADS = 10;//10个线程
        executorService =
                MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(NUM_THREADS));
        ListenableFuture<String> listenableFuture =
                executorService.submit(new Callable<String>(){
                    @Override
                    public String call() throws Exception {
                        return null;
                    }
                });
        listenableFuture.addListener(new Runnable() {
            @Override
            public void run() {
                //在Future任务完成之后运行的一些方法
                System.out.println("methodToRunOnFutureTaskCompletion");
            }
        }, executorService);

    }
}
